import { filterClassNames } from './filterClassNames';
import { EXT_NAME, GENERATE, CSS_ANNOTATION, ROOT, BEFORE_CONTENTS, AFTER_CONTENT } from '../constant';
import { getConfig } from '../config';
import { renderCss } from './preRender';

const fs = require('fs');
const path = require('path');
const shelljs = require('shelljs');
const glob = require('glob');
const { performance } = require('perf_hooks');

const writeToFile = () => {
    const cssFilePath = path.resolve(getConfig(GENERATE));
    const cssDirPath = path.resolve(getConfig(GENERATE), '..');
    // console.log(cssFilePath);
    // shelljs.rm('-rf', cssFilePath);
    if (!fs.existsSync(cssFilePath)) {
        shelljs.mkdir('-p', cssDirPath);
    }

    const cssStr = `${getConfig(BEFORE_CONTENTS) || ''}\n${CSS_ANNOTATION}${renderCss()}${getConfig(AFTER_CONTENT) || ''}`;
    fs.writeFileSync(cssFilePath, cssStr);
}

const readFile = (path: any) => {
    if (fs.existsSync(path) && fs.statSync(path).isFile()) {
        return fs.readFileSync(path, 'utf8');
    }

    return '';
}

const getAllFileClassStr = () => {
    const globSyncStr = getConfig(EXT_NAME).join('|');
    // console.log(`@/${getConfig(ROOT)}/**/*.(${globSyncStr})`);
    // console.log(process.cwd());
    // const files = glob.sync(path.join(process.cwd(), `./${getConfig(ROOT)}/**/*.(${globSyncStr})`));
    // console.log(path.join(process.cwd(), `./${getConfig(ROOT)}/**/*.@(${globSyncStr})`));
    // console.log(files);
    // console.log(glob.sync(`**/*.${globSyncStr}`));
    // 暂时这么处理，后续优化
    const files = glob.sync(`**/*.@(${globSyncStr})`, {
        ignore: ["node_modules/**"]
    });
    return files.reduce((t: any, c: any) => t + readFile(path.resolve(c)), '');
}

let startTime = 0;
let endTime = 0;
let hotReload = false;

const setTimeStart = () => {
    startTime = performance.now();
}

const setTimeEnd = () => {
    endTime = performance.now();
}

const getUseTime = () => (endTime - startTime).toFixed(2);

const logUseTime = () => {
    console.log(`autocss 生成器${hotReload ? '重载' : '初始化'}完成， 用时 ${getUseTime()}ms`);
}

export const init = (compiler: any = null) => {
    setTimeStart();
    filterClassNames(getAllFileClassStr());
    writeToFile();
    setTimeEnd();
    if (compiler) {
        compiler.hooks.done.tap('autocss-generator-done', logUseTime);
    } else {
        logUseTime();
    }
}

export const hotReloadFn = (txt: string) => {
    // console.log(txt);
    hotReload = true;
    setTimeStart();
    filterClassNames(txt);
    writeToFile();
    setTimeEnd();
    logUseTime();
}